/*jslint browser: true*/
/*global $, jQuery, alert, window*/
function getNodeListorder(node) {
    "use strict";
    var zTree = window.zTree,
        children = zTree.getNodesByParam("pId", node.pId),
        index,
        length = children.length;
    for (index = 0; index < length; index = index + 1) {
        if (children[index].id === node.id) {
            return index + 1;
        }
    }
    throw new Error("Can not found " + node.id + " in " + node.pId);
}

window.view = {
    "new_node_name": function (name_value) {
        "use strict";
        if (name_value) {
            $("#new_node_name").val(name_value);
        }
        return window.trim($("#new_node_name").val());
    },
    "new_name": function (name_value) {
        "use strict";
        if (name_value) {
            $("#new_name").val(name_value);
        }
        return window.trim($("#new_name").val());
    }
};

window.sync = {
    "char_data_ztree": function () {
        "use strict";
        window.storageRemove(window.char_all_key);
        var char_all_key = window.char_all_key,
            data_list = window.fetchData(window.storage(char_all_key), window.format.char),
            zNodes = [],
            setting = window.zTree_setting,
            index,
            length = data_list.length,
            item;
                /*
        data :[ { "id": 1, "name":"", "father_id":0, "is_kp":false, "listorder":""},
                { "id": 2, "name":"", "father_id":0, "is_kp":false, "listorder":""},]
        var zNodes =[{ id:13, pId:1, name:"禁止拖拽 1-3", isParent:true  },
                    { id:131, pId:13, name:"禁止拖拽 1-3-1", isParent:true},]
        }*/
        for (index = 0; index < length; index = index + 1) {
            item = data_list[index];
            zNodes.push({
                id: item.id,
                pId: item.father_id,
                name: item.name,
                isParent : !item.is_kp
            });
        }
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        window.storageRemove(char_all_key);
        window.zTree = $.fn.zTree.getZTreeObj("treeDemo");
    }
};

window.init = {
    "global_var": function () {
        "use strict";
        var pathname_list = location.pathname.split("/");
        window.major_id = pathname_list[pathname_list.length - 3];
        window.char_all_key = "/major/{id}/char/".format({id: window.major_id });
        window.zTree_setting = {
            view: { selectedMulti: false },
            edit : {
                enable : true,
                showRemoveBtn : false,
                showRenameBtn : false,
                drag : {
                    prev : true,
                    inner : false,
                    next : true,
                    isMove : true,
                    isCopy : false
                }
            },
            data : {
                simpleData : {
                    enable : true
                }
            },
            callback : {
                //beforeDrop : zTreeBeforeDrop,
                onDrop : window.listener.char_drop
            }
        };
        window.root_url = "/major/" + window.major_id + "/char/";
        window.zTree = null;
    },
    "zTree": function () {
        "use strict";
        window.sync.char_data_ztree();
    },
    "addEventListener": function () {
        "use strict";
        $("#expandAllBtn").bind("click", window.listener.zTree_expand);
        $("#collapseAllBtn").bind("click", window.listener.zTree_collapse);
        $("#rename").bind("click", window.listener.char_update_name);
        $("#remove").bind("click", window.listener.char_remove);
        $("#new_root_char").click(window.listener.char_root_add);
        $("#new_sub_char").bind("click", {is_kp: false}, window.listener.char_char_add);
        $("#new_kp").bind("click", {is_kp: true}, window.listener.char_char_add);
        window.hideLoading();
    }
};

window.init_func_list = ['global_var',
                         'zTree',
                        "addEventListener"];

window.listener = {
    "char_add_action": function (char_data) {
        "use strict";
        $.ajax({
            url:  window.char_all_key,
            type: "POST",
            dataType: "json",
            data: JSON.stringify(char_data),
            async: true,
            success: function (result, status) {
                var zTree = window.zTree,
                    rData = window.fetchData(result.data, window.format.char)[0],
                    parentNode = rData.father_id && zTree.getNodeByParam("id", rData.father_id);
                //ztree
                zTree.addNodes(parentNode, {
                    id : rData.id,
                    pId : rData.father_id,
                    isParent: !rData.is_kp,
                    name : rData.name
                });
                //focus
                zTree.selectNode(zTree.getNodeByParam("id", rData.id, null));
                window.hideLoading();
            }
        });

    },
    "char_root_add": function (event) {
        "use strict";
        window.loading();
        var zTree = window.zTree,
            char_name = window.view.new_node_name() || "新章节",
            char_data,
            major_id = window.major_id;
        char_data = {
            major_id : major_id,
            name : char_name,
            father_id : null,
            listorder : zTree.getNodesByParam("pId", null, null).length + 1
        };
        window.listener.char_add_action(char_data);
    },
    "char_char_add": function (event) {
        "use strict";
        var zTree = window.zTree,
            select_node_list = zTree.getSelectedNodes(),
            parentNode = select_node_list[0],
            char_name = window.view.new_node_name(),
            major_id,
            char_data,
            is_kp;
        if (select_node_list.length < 1) {
            alert("请先选择一个章节(非知识点)");
            return;
        }
        window.loading();
        if (parentNode.isParent === false) {
            parentNode = zTree.getNodeByParam("id", parentNode.pId, null);
        }
        major_id = window.major_id;
        is_kp = event.data.is_kp;
        char_name = char_name || (is_kp ? "新知识点" : "新子章节");
        char_data = {
            major_id : major_id,
            name : char_name,
            father_id : parentNode.id,
            is_kp : is_kp,
            listorder : zTree.getNodesByParam("pId", parentNode.id, null).length + 1
        };
        window.listener.char_add_action(char_data);
    },
    "zTree_expand": function (event) {
        "use strict";
        var zTree = window.zTree;
        zTree.expandAll(true);
    },
    "zTree_collapse": function () {
        "use strict";
        var zTree = window.zTree;
        zTree.expandAll(false);
    },
    "char_update_name": function (e) {
        "use strict";
        var zTree = window.zTree,
            nodes = zTree.getSelectedNodes(),
            selectedNode = nodes[0],
            newItemName = $("#new_name").val(),
            char_key;
        //invalid
        if (newItemName === "") {
            alert("请输入名称");
            return;
        }
        if (nodes.length === 0) {
            alert("请先选择一个节点");
            return;
        }
        //server
        window.loading();
        char_key = window.char_all_key + selectedNode.id + "/";
        $.ajax({
            url : char_key,
            type : 'PUT',
            dataType: "json",
            data : JSON.stringify({ "name" : newItemName }),
            success : function (result, status) {
                var rData = window.fetchData(result.data, window.format.char)[0];
                //ztree
                selectedNode.name = rData.name;
                zTree.updateNode(selectedNode);
                window.hideLoading();
            }
        });
    },
    "char_remove": function (e) {
        "use strict";
        //invalid
        var zTree = window.zTree,
            nodes = zTree.getSelectedNodes(),
            selectedNode = nodes[0],
            char_key;
        if (nodes.length === 0) {
            alert("请先选择一个节点");
            return;
        }
        //server
        window.loading();
        char_key = window.char_all_key + selectedNode.id + "/";
        $.ajax({
            url: char_key,
            type: "DELETE",
            dataType: "json",
            success: function (result, status) {
                zTree.removeNode(selectedNode, true);
                window.hideLoading();
            }
        });
    },
    "char_drop": function (event, treeId, treeNodes, targetNode, moveType) {
        "use strict";
        window.loading();
        var add = 0,
            dragNode = treeNodes[0],
            data_on_drag = {},
            char_key = window.char_all_key + dragNode.id + "/";
        data_on_drag.father_id = dragNode.pId;
        data_on_drag.listorder = getNodeListorder(dragNode);
        $.ajax({
            url: char_key,
            type: "PUT",
            dataType: "json",
            async: true,
            data: JSON.stringify(data_on_drag),
            success: function (result, status) {
                window.hideLoading();
            }
        });
    }
};